package com.happe.foodeasy.winter.type.constraint;

import com.happe.foodeasy.constraint.annotation.IdCustom;
import com.happe.foodeasy.constraint.annotation.NotNullCustomer;
import com.happe.foodeasy.helper.AnnotationHelper;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * This class is used to generate constraint for database field.
 * Created by wubin on 2016-05-21.
 */
@Component
public class TypeConstraintHelper {
    public List<String> parseTargetFieldConstraint(Field oneField) {
        List<String> result = new ArrayList<>();
        String targetClassName = oneField.getType().getSimpleName();
        boolean isForeignKey = AnnotationHelper.checkRelationalAnnotationForField(oneField);
        if (isForeignKey) {
            result.add("references " + targetClassName + "(id) ");
        }

        Annotation[] annotations = oneField.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotationIsTargetType(annotation, IdCustom.class)) {
                result.add("primary key ");
            } else if (annotationIsTargetType(annotation, NotNullCustomer.class)) {
                result.add("not null ");
            }
        }

        return result;
    }

    private boolean annotationIsTargetType(Annotation sourceAnnotation, Class<? extends Annotation> targetAnnotation) {
        return targetAnnotation.isAssignableFrom(sourceAnnotation.annotationType());
    }
}
